package de.pharmacontrol.rfcserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.logging.Logger;

import com.sap.conn.jco.ext.ServerDataEventListener;
import com.sap.conn.jco.ext.ServerDataProvider;

import de.pharmacontrol.jdni.JdniRepository;

public class PceServerDataProvider implements ServerDataProvider{

	private final String fileName = "server.xml";

	public Properties getServerProperties(String serverName) {
		Properties connectProperties = null;
		try {
			connectProperties = JdniRepository.getInstance().getServerProperties();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		if (connectProperties != null){
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info("ServerProperties received from: " + JdniRepository.JCO_SERVER_CONTEXT);
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(""+String.valueOf(connectProperties));
			return connectProperties;
		}
		File cfg = new File(fileName);
		if (cfg.exists()){
			try {
				connectProperties = new Properties();
				FileInputStream in = new FileInputStream(cfg);
				connectProperties.loadFromXML(in);
				in.close();
			} catch (Exception e) {
				System.err.println("Unable to read the server file " + cfg.getName() + ": " + e.getMessage());
				connectProperties =  getDefaultProps();
			}
		}else{
			connectProperties = getDefaultProps();
			createFile(cfg, connectProperties);
		}
		return connectProperties;
	}

	private Properties getDefaultProps(){
		
		Properties props = new Properties();
		props.setProperty(ServerDataProvider.JCO_GWHOST, "10.1.130.17");
		props.setProperty(ServerDataProvider.JCO_GWSERV, "sapgw00");
		props.setProperty(ServerDataProvider.JCO_PROGID, "PCE_RFC_SERVICE_D");
		props.setProperty(ServerDataProvider.JCO_REP_DEST, "ABAP_AS_WITH_POOL");
		props.setProperty(ServerDataProvider.JCO_CONNECTION_COUNT, "2");
		
		return props;
	}
	
	private void createFile(File cfg, Properties properties) {
		if (!cfg.exists()) {
			try {
				FileOutputStream fos = new FileOutputStream(cfg, false);
				properties.storeToXML(fos, "PCE Server");
				fos.close();
			} catch (Exception e) {
				System.err.println("Unable to create the server file " + cfg.getName()+": "+ e.getMessage());
			}
		}
	}
	

	@Override
	public boolean supportsEvents() {
		return false;
	}

	@Override
	public void setServerDataEventListener(ServerDataEventListener eventListener) {
	}

}
